<template>
  <div class="wrap">
    <div class="search-wrap">
      <el-input
        v-model.trim="search.username"
        @keyup.enter="getUserList"
        placeholder="模糊搜索用户名"
        style="width: 350px"
      />
      <el-button class="search-class" type="primary" @click.stop="getUserList"
        >查询</el-button
      >
    </div>
    <el-table :data="userList" style="width: 100%">
      <!-- <el-table-column prop="id" label="id"> </el-table-column> -->
      <el-table-column prop="username" label="姓名"> </el-table-column>
      <el-table-column label="所属部门">
        <template v-slot="scope">
          {{ scope.row.department?.departmentname }}
        </template>
      </el-table-column>
      <el-table-column label="拥有角色">
        <template v-slot="scope">
          {{ scope.row.roles.map((role) => role.rolename).join("、") }}
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="注册时间"> </el-table-column>
      <el-table-column fixed="right" label="操作" width="280">
        <template v-slot="scope">
          <el-button
            @click.stop="userJoinDepartment(scope.row)"
            type="primary"
            size="small"
          >
            加入部门
          </el-button>
          <el-button
            @click.stop="userAddRole(scope.row)"
            type="primary"
            size="small"
          >
            分配角色
          </el-button>
          <el-popconfirm
            title="确认要删除该列?"
            confirm-button-text="是"
            cancel-button-text="否"
            @confirm="deleteRow(scope.row)"
          >
            <template #reference>
              <el-button> 删除 </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分配角色 -->
    <el-dialog
      v-model="dialogRoleVisible"
      :close-on-click-modal="false"
      title="授权"
    >
      <el-form :model="form" label-position="top">
        <el-form-item label="角色（多选）" label-width="140px">
          <el-checkbox-group v-model="form.roles">
            <el-checkbox
              :label="role.id"
              v-for="(role, index) in allRoleList"
              :key="index"
              >{{ role.rolename }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogRoleVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmRole"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 加入部门 -->
    <el-dialog
      v-model="dialogDepartmentVisible"
      :close-on-click-modal="false"
      title="部门选择"
    >
      <el-form :model="form" label-position="top">
        <el-form-item label="部门（单选）" label-width="140px">
          <el-radio-group v-model="form.departmentId">
            <el-radio
              :label="department.id"
              v-for="(department, index) in allDepartmentList"
              :key="index"
              >{{ department.departmentname }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogDepartmentVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmDepartment">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import request from "utils/request";
import { ElMessage, ElMessageBox } from "element-plus";

export default {
  name: "JddChromePluginsUserList",

  data() {
    return {
      dialogRoleVisible: false,
      dialogDepartmentVisible: false,
      search: {
        username: "",
      },
      form: {
        id: "",
        roles: [],
        departmentId: "",
      },
      userList: [],
      allRoleList: [],
      allDepartmentList: [],
    };
  },

  async mounted() {
    await this.getUserList();
    await this.getAllRoleList();
    await this.getAllDepartmentList();
  },
  watch: {
    dialogRoleVisible: {
      handler(value) {
        if (!value) {
          Object.assign(this.form, {
            id: "",
            roles: [],
          });
        }
      },
    },
    dialogDepartmentVisible: {
      handler(value) {
        if (!value) {
          Object.assign(this.form, {
            id: "",
            departmentId: "",
          });
        }
      },
    },
  },
  methods: {
    async getUserList() {
      let ret = await request.get("/user/list", {
        username: this.search.username,
      });
      if (ret.code == 200) {
        this.userList = ret.data.data || [];
      }
    },
    async getAllRoleList() {
      let ret = await request.get("/role/list", {});
      if (ret.code == 200) {
        this.allRoleList = ret.data[0] || [];
      }
    },
    async getAllDepartmentList() {
      let ret = await request.get("/department/list", {});
      if (ret.code == 200) {
        this.allDepartmentList = ret.data[0] || [];
      }
    },
    async findUserSelfRoles(userId) {
      let ret = await request.get(`/user/hasroles/${userId}`);
      if (ret.code == 200) {
        this.form.roles = ret.data.map((item) => item.id) || [];
      }
    },
    async userAddRole(row) {
      this.form.id = row.id;
      this.findUserSelfRoles(row.id);
      this.dialogRoleVisible = true;
    },
    async confirmRole() {
      let ret = await request.post("/user/add/role", {
        userId: this.form.id,
        roleIds: this.form.roles,
      });
      if (ret.code == 200) {
        this.$message({
          message: "修改成功",
          type: "success",
        });
        this.getUserList();
        this.dialogRoleVisible = false;
      } else {
        this.$message({
          message: ret.message,
          type: "error",
        });
      }
    },
    async findUserSelfDepartment(userId) {
      let ret = await request.get(`/user/department/${userId}`);
      if (ret.code == 200) {
        this.form.departmentId = ret.data.id;
      }
    },
    userJoinDepartment(row) {
      this.form.id = row.id;
      this.dialogDepartmentVisible = true;
      this.findUserSelfDepartment(row.id);
    },
    async confirmDepartment() {
      let ret = await request.post("/user/join/department", {
        userId: this.form.id,
        departmentId: this.form.departmentId,
      });
      if (ret.code == 200) {
        this.$message({
          message: "修改成功",
          type: "success",
        });
        this.getUserList();
        this.dialogDepartmentVisible = false;
      } else {
        this.$message({
          message: ret.message,
          type: "error",
        });
      }
    },
    async deleteRow(user) {
      let ret = await request.delete(`/user/${user.id}`, {});
      if (ret.code == 200) {
        ElMessage.success("删除成功");
        this.getUserList();
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.wrap {
  .headPictureCol {
    width: 32px;
    height: 32px;
    overflow: hidden;
    border-radius: 50%;
  }
  .search-wrap {
    display: flex;
    margin-bottom: 15px;
    .search-class {
      margin-left: 20px;
    }
  }
}
</style>
